package com.dailyblue.java.spring.rocketmq.mq02.controller;

import com.dailyblue.java.spring.rocketmq.mq02.util.JsonResult;
import com.dailyblue.java.spring.rocketmq.mq02.util.ResultTool;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RequestMapping("/second")
@RestController
public class SecondRocketMQController {
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @GetMapping("/a")
    public JsonResult a(String tags, Integer num) {
        SendResult result = rocketMQTemplate.syncSend("TopicA:" + tags, "sync:" + num);
        return ResultTool.success(result);
    }

    @GetMapping("/b")
    public JsonResult b(String tags, Integer num) throws Exception {
        final JsonResult[] result = {null};
        rocketMQTemplate.asyncSend("TopicA:" + tags, "async:" + num, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                result[0] = ResultTool.success(sendResult);
            }

            @Override
            public void onException(Throwable throwable) {
                result[0] = ResultTool.fail();
            }
        });
        Thread.sleep(3000);
        return result[0];
    }

    @GetMapping("/c")
    public JsonResult c(String tags, Integer num) {
        rocketMQTemplate.sendOneWay("TopicA:" + tags, "oneway:" + num);
        return null;
    }
}
